package exp3;

public class MyArrayQueue<T> implements MyQueue<T> {
    private T[] queue;
    private int size;
    private int headMarker, tailMarker;
    private int defaultSize = 2;

    public MyArrayQueue() {
        queue = (T[]) new Object[defaultSize];
        size = 0;
        headMarker = -1;
        tailMarker = 0;
    }

    @Override
    public void offer(T value) {
        headMarker++;
        if (headMarker >= defaultSize) {
            kuoRong();
        }
        queue[headMarker] = value;
        size++;
    }

    @Override
    public void poll() {
        tailMarker++;
        size--;
    }

    @Override
    public T peek() {
        return queue[headMarker];
    }

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder("[");
        if (size > 0) {
            str.append(queue[headMarker]);
            for (int i = headMarker - 1; i >= tailMarker; i--) {
                str.append(", ");
                str.append(queue[i]);
            }
        }
        str.append("]");
        return str.toString();
    }

    private void kuoRong() {
        defaultSize *= 2;
        T[] queue2 = (T[]) new Object[defaultSize];
        for (int i = 0; i < defaultSize / 2; i++) {
            queue2[i] = queue[i];
        }
        queue = queue2;
    }

    public static void main(String[] args) {
        MyArrayQueue<Integer> queue = new MyArrayQueue<>();
        for (int i = 0; i < 5; i++) {
            queue.offer(i);
            System.out.println(queue);
        }
        for (int i = 0; i < 5; i++) {
            queue.poll();
            System.out.println(queue);
        }
    }
}
